/**
 *单位(派出所)下拉
 */

import { Select, SelectProps } from 'antd';
import { memo, useEffect, useImperativeHandle, useState } from 'react';

import { ISelectMutiRef } from '../../types';
import { useGetSqUnit } from '../../service/unit-service';
import { DefaultOptionType } from 'antd/es/select';

interface IRoleSelectProps extends SelectProps<number> {
    handleChange: (value: string[]) => void;
    onRef?: React.MutableRefObject<ISelectMutiRef | undefined>;
    unitId: string;
    sqUnitId?: string[];

}

const SqUnitSelectMu = ({ handleChange, onRef, unitId, sqUnitId }: IRoleSelectProps) => {
    const [queryParams, setQueryParams] = useState<{ unitId: string, }>({ unitId: '' })

    useEffect(() => {
        if (unitId) {
            setQueryParams({ unitId });
        }
    }, [unitId])
    const { isLoading, isError, data: dataSource } = useGetSqUnit(queryParams);

    const [val, setVal] = useState<string[]>();
    useEffect(() => {
        if (dataSource && dataSource?.length > 0) {
            if (sqUnitId) {
                setVal([...sqUnitId])
            }
        } else {
            setVal([])
        }
    }, [dataSource, unitId])
    const onChange = (value: string[]) => {
        setVal(value);
        handleChange(value);
    };


    /**向外暴露的重置方法 */
    useImperativeHandle(onRef, () => ({
        rest: () => {
            setVal(undefined);
        },
        fill: (unitId) => {
            setVal(unitId);
        },
        getData: () => {
            return val;
        }
    }));
    return (

        <Select showSearch
            filterOption={(input, option) => {
                return (option?.children ?? '').includes(input as string & Omit<DefaultOptionType, "children">);
            }}
            
            mode="multiple" placeholder={'请选择社区'} value={val} onChange={onChange} loading={isLoading} allowClear>
            {isError
                ? null
                : dataSource?.map((data) => {
                    return <Select.Option key={data.sqUnitId} value={data.sqUnitId}>
                        {data.sqUnitName}
                    </Select.Option>
                })}
        </Select >

    );
};


export default memo(SqUnitSelectMu)